<template>
  <div class="user-orders-container">
    <div class="page-header">
      <h1>我的订单</h1>
      <div class="filter-bar">
        <el-select v-model="statusFilter" placeholder="订单状态" clearable @change="filterOrders">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="filterOrders"
        />
        
        <el-input
          v-model="searchKeyword"
          placeholder="搜索订单号/商品名称"
          clearable
          @keyup.enter="filterOrders"
          @clear="filterOrders"
        >
          <template #suffix>
            <el-button :icon="Search" circle @click="filterOrders" />
          </template>
        </el-input>
      </div>
    </div>
    
    <div class="orders-content">
      <el-card v-if="loading" class="loading-placeholder">
        <el-skeleton :rows="5" animated />
      </el-card>
      
      <div v-else-if="orders.length === 0" class="empty-state">
        <el-empty description="暂无订单记录" />
        <el-button type="primary" @click="goToProducts">去购物</el-button>
      </div>
      
      <template v-else>
        <el-card v-for="order in orders" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-date">下单时间: {{formatDate(order.orderDate)}}</span>
              <span class="order-number">订单号: {{order.orderNumber}}</span>
            </div>
            <div class="order-status" :class="getStatusClass(order.status)">
              {{getStatusText(order.status)}}
            </div>
          </div>
          
          <el-divider />
          
          <div class="order-items">
            <div v-if="!order.orderItems || order.orderItems.length === 0" class="empty-order-items">
              <p>订单中没有商品信息</p>
            </div>
            <div v-else v-for="item in order.orderItems" :key="item.id" class="order-item">
              <div class="product-info">
                <el-image 
                  :src="item.productImage || 'https://placeholder.pics/svg/150x150'" 
                  fit="cover"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{item.productName || '未知商品'}}</div>
                  <div class="product-specs">{{item.productSpecs || ''}}</div>
                </div>
              </div>
              
              <div class="item-price">¥{{(item.price || item.unitPrice || 0).toFixed(2)}}</div>
              <div class="item-quantity">×{{item.quantity || 1}}</div>
              <div class="item-subtotal">¥{{((item.price || item.unitPrice || 0) * (item.quantity || 1)).toFixed(2)}}</div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-total">
              共 {{getTotalItems(order)}} 件商品，总计：
              <span class="total-amount">¥{{(order.totalAmount || 0).toFixed(2)}}</span>
            </div>
            
            <div class="order-actions">
              <el-button 
                v-if="order.status === 'AWAITING_PAYMENT' || order.status === 'PENDING'" 
                type="primary" 
                size="small"
                @click="handlePayment(order.id)"
              >
                去支付
              </el-button>
              
              <el-button 
                v-if="order.status === 'SHIPPED'" 
                type="success" 
                size="small"
                @click="confirmReceipt(order.id)"
              >
                确认收货
              </el-button>
              
              <el-button 
                v-if="['DELIVERED', 'COMPLETED'].includes(order.status)" 
                type="warning" 
                size="small"
                @click="writeReview(order.id)"
              >
                评价
              </el-button>
              
              <el-button size="small" @click="viewOrderDetails(order.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
        
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="totalOrders"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { useUserStore } from '../../stores/user';
import { getOrdersByCustomerId, getOrdersByStatus, getOrdersByDateRange, searchOrders, updateOrderStatus } from '../../api/order';

const router = useRouter();
const userStore = useUserStore();

// 订单状态选项
const statusOptions = [
  { value: 'PENDING', label: '待处理' },
  { value: 'AWAITING_PAYMENT', label: '待付款' },
  { value: 'PAID', label: '已付款' },
  { value: 'PROCESSING', label: '处理中' },
  { value: 'SHIPPED', label: '已发货' },
  { value: 'DELIVERED', label: '已送达' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' },
  { value: 'REFUNDED', label: '已退款' }
];

// 页面状态
const loading = ref(true);
const orders = ref<any[]>([]);
const totalOrders = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const statusFilter = ref('');
const dateRange = ref<[string, string] | null>(null);
const searchKeyword = ref('');

// 数据适配器，将服务器返回的数据转换为统一的格式
const adaptOrderData = (rawOrder: any) => {
  if (!rawOrder) return null;
  
  const adaptedOrder = {
    id: rawOrder.id,
    orderNumber: rawOrder.orderNumber || '',
    orderDate: rawOrder.orderDate || rawOrder.createTime || new Date().toISOString(),
    status: rawOrder.status || 'PENDING',
    totalAmount: parseFloat(rawOrder.totalAmount || 0),
    shippingCost: parseFloat(rawOrder.shippingCost || 0),
    taxAmount: parseFloat(rawOrder.taxAmount || 0),
    trackingNumber: rawOrder.trackingNumber || '',
    orderItems: []
  };
  
  // 处理订单项
  if (rawOrder.orderItems && Array.isArray(rawOrder.orderItems)) {
    adaptedOrder.orderItems = rawOrder.orderItems.map((item: any) => ({
      id: item.id,
      productName: item.productName,
      productSpecs: item.productSpecs || '',
      productImage: item.productImage || '',
      price: parseFloat(item.price || item.unitPrice || 0),
      quantity: parseInt(item.quantity || 1),
      subtotal: parseFloat(item.subtotal || 0)
    }));
  } else {
    // 订单项为空或不是数组
    console.warn('订单缺少订单项信息:', rawOrder);
    adaptedOrder.orderItems = [];
  }
  
  return adaptedOrder;
};

// 获取客户订单
const fetchOrders = async () => {
  loading.value = true;
  
  try {
    const customerId = userStore.customerId;
    if (!customerId) {
      ElMessage.error('无法获取客户信息');
      console.error('获取订单失败：用户ID为空', userStore);
      return;
    }
    
    console.log('开始请求订单数据，客户ID:', customerId);
    const response = await getOrdersByCustomerId(
      customerId, 
      currentPage.value - 1, 
      pageSize.value
    );
    
    console.log('获取到订单响应:', response);
    
    if (response && response.code === 200) {
      let rawOrders = [];
      
      // 检查响应格式并适当处理
      if (response.data && Array.isArray(response.data)) {
        // 返回的是直接数组格式
        console.log('订单数据是数组格式');
        rawOrders = response.data;
        totalOrders.value = response.data.length;
      } else if (response.data && response.data.content) {
        // 返回的是分页格式
        console.log('订单数据是分页格式');
        rawOrders = response.data.content;
        totalOrders.value = response.data.totalElements || 0;
      } else if (response.data) {
        // 未知格式，尝试处理
        console.log('未知数据格式，尝试处理:', response.data);
        rawOrders = Array.isArray(response.data) ? response.data : [response.data];
        totalOrders.value = rawOrders.length;
      } else {
        console.warn('订单数据为空');
        rawOrders = [];
        totalOrders.value = 0;
      }
      
      // 适配数据格式
      orders.value = rawOrders
        .map(order => adaptOrderData(order))
        .filter(Boolean);
      
      console.log('处理后的订单数据:', orders.value);
    } else {
      console.error('获取订单失败:', response);
      ElMessage.error(response?.message || '获取订单失败');
    }
  } catch (error) {
    console.error('获取订单发生异常:', error);
    ElMessage.error('获取订单时发生错误');
    
    // 临时测试数据，实际生产环境应该删除
    orders.value = [
      {
        id: 1,
        orderNumber: 'ORD2023100101',
        orderDate: '2023-10-01T10:30:00',
        status: 'DELIVERED',
        totalAmount: 199.5,
        orderItems: [
          {
            id: 1, 
            productName: '水润保湿面膜',
            productSpecs: '25ml×5片',
            productImage: 'https://img.freepik.com/free-photo/pink-cosmetics-set-make-up-tools-products_23-2148690805.jpg',
            price: 39.9,
            quantity: 2
          },
          {
            id: 2, 
            productName: '亮肤精华液',
            productSpecs: '30ml',
            productImage: 'https://img.freepik.com/free-photo/flat-lay-natural-crystal-deodorant-bottle_23-2149206402.jpg',
            price: 119.7,
            quantity: 1
          }
        ]
      },
      {
        id: 2,
        orderNumber: 'ORD2023092501',
        orderDate: '2023-09-25T14:20:00',
        status: 'SHIPPED',
        totalAmount: 158.0,
        orderItems: [
          {
            id: 3, 
            productName: '防晒喷雾',
            productSpecs: '60ml',
            productImage: 'https://img.freepik.com/free-photo/arrangement-with-beauty-bag-cosmetics_23-2148132196.jpg',
            price: 158.0,
            quantity: 1
          }
        ]
      }
    ];
    totalOrders.value = 2;
    console.log('使用测试数据代替:', orders.value);
  } finally {
    loading.value = false;
  }
};

// 筛选订单
const filterOrders = async () => {
  loading.value = true;
  currentPage.value = 1;
  
  try {
    let response = null;
    let rawOrders = [];
    
    if (statusFilter.value) {
      // 按状态筛选
      response = await getOrdersByStatus(
        statusFilter.value,
        0,
        pageSize.value
      );
      
    } else if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      // 按日期范围筛选
      const [start, end] = dateRange.value;
      response = await getOrdersByDateRange(
        start,
        end,
        0,
        pageSize.value
      );
      
    } else if (searchKeyword.value.trim()) {
      // 按关键词搜索
      response = await searchOrders(
        searchKeyword.value.trim(),
        0,
        pageSize.value
      );
      
    } else {
      // 无筛选条件，获取全部
      await fetchOrders();
      return;
    }
    
    console.log('筛选响应:', response);
    
    if (response && response.code === 200) {
      // 处理返回数据
      if (response.data && Array.isArray(response.data)) {
        rawOrders = response.data;
        totalOrders.value = response.data.length;
      } else if (response.data && response.data.content) {
        rawOrders = response.data.content;
        totalOrders.value = response.data.totalElements || 0;
      } else if (response.data) {
        rawOrders = Array.isArray(response.data) ? response.data : [response.data];
        totalOrders.value = rawOrders.length;
      } else {
        rawOrders = [];
        totalOrders.value = 0;
      }
      
      // 适配数据格式
      orders.value = rawOrders
        .map(order => adaptOrderData(order))
        .filter(Boolean);
      
      console.log('筛选后的订单数据:', orders.value);
    } else {
      console.error('筛选订单失败:', response);
      ElMessage.error(response?.message || '筛选订单失败');
    }
  } catch (error) {
    console.error('筛选订单异常:', error);
    ElMessage.error('筛选订单时发生错误');
  } finally {
    loading.value = false;
  }
};

// 页码变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchOrders();
};

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: {[key: string]: string} = {
    'PENDING': '待处理',
    'AWAITING_PAYMENT': '待付款',
    'PAID': '已付款',
    'PROCESSING': '处理中',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
    'REFUNDED': '已退款'
  };
  
  return statusMap[status] || status;
};

// 获取订单状态类名
const getStatusClass = (status: string) => {
  const statusClassMap: {[key: string]: string} = {
    'PENDING': 'status-pending',
    'AWAITING_PAYMENT': 'status-awaiting',
    'PAID': 'status-paid',
    'PROCESSING': 'status-processing',
    'SHIPPED': 'status-shipped',
    'DELIVERED': 'status-delivered',
    'COMPLETED': 'status-completed',
    'CANCELLED': 'status-cancelled',
    'REFUNDED': 'status-refunded'
  };
  
  return statusClassMap[status] || '';
};

// 获取订单总商品数
const getTotalItems = (order: any) => {
  if (!order.orderItems || !Array.isArray(order.orderItems)) {
    return 0;
  }
  return order.orderItems.reduce((total: number, item: any) => total + (item.quantity || 1), 0);
};

// 日期格式化
const formatDate = (dateString: string | number[] | any) => {
  if (!dateString) {
    return '未知日期';
  }
  
  try {
    // 处理数组格式的日期 [year, month, day, hour, minute, second]
    if (Array.isArray(dateString)) {
      return formatArrayDate(dateString);
    }
    
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      return dateString; // 如果转换失败，返回原始字符串
    }
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateString;
  }
};

// 格式化数组格式的日期
const formatArrayDate = (dateArray: number[]) => {
  if (!dateArray || dateArray.length < 3) {
    return '日期格式错误';
  }
  
  try {
    const year = dateArray[0];
    const month = dateArray[1].toString().padStart(2, '0');
    const day = dateArray[2].toString().padStart(2, '0');
    
    let result = `${year}-${month}-${day}`;
    
    // 如果有时分秒信息
    if (dateArray.length >= 6) {
      const hour = dateArray[3].toString().padStart(2, '0');
      const minute = dateArray[4].toString().padStart(2, '0');
      const second = dateArray[5].toString().padStart(2, '0');
      result += ` ${hour}:${minute}:${second}`;
    }
    
    return result;
  } catch (e) {
    console.error('数组日期格式化错误:', e);
    return dateArray.join(',');
  }
};

// 去商品页
const goToProducts = () => {
  router.push('/user/products');
};

// 查看订单详情
const viewOrderDetails = (orderId: number) => {
  router.push(`/user/order/${orderId}`);
};

// 支付订单
const handlePayment = (orderId: number) => {
  router.push(`/user/payment/${orderId}`);
};

// 确认收货
const confirmReceipt = (orderId: number) => {
  ElMessageBox.confirm(
    '确认已收到商品？',
    '确认收货',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await updateOrderStatus(orderId, 'DELIVERED');
      if (response.code === 200) {
        ElMessage.success('确认收货成功');
        fetchOrders(); // 重新加载订单列表
      } else {
        ElMessage.error(response.message || '确认收货失败');
      }
    } catch (error) {
      console.error('确认收货异常:', error);
      ElMessage.error('确认收货时发生错误');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 评价商品
const writeReview = (orderId: number) => {
  router.push(`/user/review/${orderId}`);
};

// 页面加载时获取订单
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.user-orders-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100%;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-info {
  display: flex;
  gap: 20px;
  color: #606266;
  font-size: 14px;
}

.order-status {
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.status-pending { color: #909399; }
.status-awaiting { color: #E6A23C; }
.status-paid { color: #409EFF; }
.status-processing { color: #67C23A; }
.status-shipped { color: #9254de; }
.status-delivered { color: #1989FA; }
.status-completed { color: #67C23A; }
.status-cancelled { color: #F56C6C; }
.status-refunded { color: #909399; }

.order-items {
  margin-bottom: 16px;
}

.order-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 10px;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.product-specs {
  font-size: 12px;
  color: #909399;
}

.item-price, .item-quantity, .item-subtotal {
  flex: 0 0 100px;
  text-align: center;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
}

.order-total {
  font-size: 14px;
  color: #606266;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #F56C6C;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state .el-button {
  margin-top: 20px;
}

.loading-placeholder {
  padding: 20px;
}
</style> 